package com.guyan.controller;

import com.github.pagehelper.PageInfo;
import com.guyan.entity.Order;
import com.guyan.form.OrderForm;
import com.guyan.service.OrderService;
import com.guyan.vo.LayuiVo;
import com.guyan.vo.ResultVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;

/**
 * ClassName： OrderController
 * Date： 2021/6/15 20:30
 *
 * @author 孤焰
 * @version 1.0
 **/

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @GetMapping("/orderList")
    public LayuiVo orderList(@RequestParam(defaultValue = "1") Integer page,
                             @RequestParam(defaultValue = "10") Integer limit,
                             Order order, Date startDate, Date endDate) {
        System.out.println(startDate);
        System.out.println(endDate);
        PageInfo pageInfo = orderService.orderList(page, limit, order, startDate, endDate);

        return LayuiVo.success(pageInfo.getTotal(), pageInfo.getList());
    }

    @PostMapping("/addOrder")
    public ResultVo addOrder(@RequestBody @Valid OrderForm orderForm, BindingResult bindingResult) {
        if (bindingResult.getErrorCount() > 0) {
            return ResultVo.error(7000, bindingResult.getAllErrors().get(0).getDefaultMessage());
        }

        Order order = new Order();
        BeanUtils.copyProperties(orderForm, order);

        return orderService.addOrder(order);
    }

    @PostMapping("/updateOrderById")
    public ResultVo updateOrderById(@RequestBody Order order) {
        return orderService.updateOrderById(order);
    }

    @PostMapping("/batchDelOrder")
    public ResultVo batchDelOrder(@RequestBody Integer[] ids) {
        if (ids == null || ids.length == 0) {
            return ResultVo.error(5001, "未选择要删除的订单");
        }

        return orderService.batchDelOrder(ids);
    }
}
